---
title: FPDF_GetLastError
description: Get the error code for the last failed PDFium operation
searchable: true
---

# FPDF_GetLastError

`FPDF_GetLastError()`

## Description

Retrieves the error code for the last failed PDFium operation. This function is particularly useful after PDF document loading functions (like `FPDF_LoadMemDocument`) return null, indicating a failure. The error code provides more information about what went wrong.

## Prerequisites

This example uses the `initializePdfium` helper function from our [Getting Started](/docs/pdfium/getting-started#initializing-pdfium) guide. Make sure to include this function in your code before trying the examples below.

## Parameters

This function doesn't take any parameters.

## Return Value

Returns an integer error code indicating the cause of the last error. The meaning of each error code is as follows:

| Code | Constant | Meaning |
|------|----------|---------|
| 0 | `FPDF_ERR_SUCCESS` | No error (success) |
| 1 | `FPDF_ERR_UNKNOWN` | Unknown error |
| 2 | `FPDF_ERR_FILE` | File not found or could not be opened |
| 3 | `FPDF_ERR_FORMAT` | File not in PDF format or corrupted |
| 4 | `FPDF_ERR_PASSWORD` | Password required or incorrect password |
| 5 | `FPDF_ERR_SECURITY` | Unsupported security scheme |
| 6 | `FPDF_ERR_PAGE` | Page not found or content error |
| 7 | `FPDF_ERR_XFALOAD` | XFA load error |
| 8 | `FPDF_ERR_XFALAYOUT` | XFA layout error |

## Interactive Example

Try opening a password-protected PDF with and without a password. This example demonstrates how to handle the common error code 4 (password required):

import GetLastErrorDemo from '../code-examples/get-last-error-example.preview';

<GetLastErrorDemo />

## Example

```typescript
// Note: The initializePdfium function is a helper that initializes the PDFium library.
// For the full implementation, see: /docs/pdfium/getting-started
import { initializePdfium } from './initialize-pdfium';

async function openProtectedPdf(pdfData: Uint8Array, password?: string) {
  // Step 1: Initialize PDFium
  const pdfium = await initializePdfium();
  
  // Step 2: Load the PDF document
  const filePtr = pdfium.pdfium.wasmExports.malloc(pdfData.length);
  pdfium.pdfium.HEAPU8.set(pdfData, filePtr);
  
  // Convert password to null-terminated UTF-8 string pointer if provided
  let passwordPtr = 0;
  if (password) {
    const encoder = new TextEncoder();
    const passwordBytes = encoder.encode(password + '\0');
    passwordPtr = pdfium.pdfium.wasmExports.malloc(passwordBytes.length);
    pdfium.pdfium.HEAPU8.set(passwordBytes, passwordPtr);
  }
  
  // Try to load the PDF document with optional password
  const docPtr = pdfium.FPDF_LoadMemDocument(filePtr, pdfData.length, passwordPtr);
  
  // Clean up password memory if allocated
  if (passwordPtr) {
    pdfium.pdfium.wasmExports.free(passwordPtr);
  }
  
  // Check if document loaded successfully
  if (!docPtr) {
    const errorCode = pdfium.FPDF_GetLastError();
    pdfium.pdfium.wasmExports.free(filePtr);
    
    // Map error code to a message
    let errorMessage;
    switch (errorCode) {
      case 0: errorMessage = 'No error'; break;
      case 1: errorMessage = 'Unknown error'; break;
      case 2: errorMessage = 'File not found or could not be opened'; break;
      case 3: errorMessage = 'File not in PDF format or corrupted'; break;
      case 4: errorMessage = 'Password required or incorrect password'; break;
      case 5: errorMessage = 'Unsupported security scheme'; break;
      case 6: errorMessage = 'Page not found or content error'; break;
      case 7: errorMessage = 'XFA load error'; break;
      case 8: errorMessage = 'XFA layout error'; break;
      default: errorMessage = `Unknown error code: ${errorCode}`; break;
    }
    
    // Return error details
    return {
      success: false,
      errorCode,
      errorMessage
    };
  }
  
  try {
    // Document loaded successfully - get basic info
    const pageCount = pdfium.FPDF_GetPageCount(docPtr);
    
    return {
      success: true,
      pageCount,
      errorCode: 0,
      errorMessage: 'PDF opened successfully'
    };
  } finally {
    // Clean up resources
    pdfium.FPDF_CloseDocument(docPtr);
    pdfium.pdfium.wasmExports.free(filePtr);
  }
}

// Usage example
async function handlePdfWithPasswordCheck() {
  try {
    // First try without password
    const response = await fetch('protected.pdf');
    const buffer = await response.arrayBuffer();
    const pdfData = new Uint8Array(buffer);
    
    let result = await openProtectedPdf(pdfData);
    
    if (!result.success && result.errorCode === 4) {
      console.log('PDF requires a password');
      
      // Get password from user (simplified for example)
      const password = prompt('Please enter the PDF password:');
      
      if (password) {
        // Try again with password
        result = await openProtectedPdf(pdfData, password);
        
        if (result.success) {
          console.log(`Successfully opened PDF with ${result.pageCount} pages`);
        } else {
          console.error(`Failed to open PDF: ${result.errorMessage}`);
        }
      }
    } else if (result.success) {
      console.log(`Successfully opened PDF with ${result.pageCount} pages`);
    } else {
      console.error(`Failed to open PDF: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error processing PDF:', error);
  }
}
```

## Best Practices

1. **Always check for errors**: After operations that might fail (especially document loading), check for errors using `FPDF_GetLastError` if the function returns an error indicator.

2. **Provide meaningful error messages**: Map the error codes to descriptive error messages to help users understand what went wrong.

3. **Handle specific error types**: Different error codes call for different responses. For example, a password error (code 4) might prompt the user for a password, while a format error (code 3) might indicate the file is corrupt.

4. **Clean up resources**: Even when errors occur, make sure to free allocated memory and close any resources that were successfully opened.

5. **Error context**: When throwing errors based on PDFium error codes, include additional context about the operation that failed to make debugging easier.

## Error Handling Strategies

1. **Password-protected PDFs**: If you get error code 4 (password required), you can prompt the user for a password and try loading the document again.

2. **Corrupted files**: Error code 3 often indicates file corruption. Consider validating PDF files before attempting to open them.

3. **Missing files**: Error code 2 suggests the file wasn't found. Check file paths and availability.

4. **XFA forms**: Error codes 7 and 8 relate to XFA forms, which are a complex form technology in PDFs. PDFium has limited support for XFA forms.

## Related Functions

- [FPDF_LoadMemDocument](/docs/pdfium/functions/FPDF_LoadMemDocument) - Load a PDF document from memory
- [FPDF_CloseDocument](/docs/pdfium/functions/FPDF_CloseDocument) - Close a loaded PDF document